package com.ziyia.jsontest;

import android.content.Context;
import android.util.Log;

import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.junit.Test;
import org.junit.runner.RunWith;

import java.lang.reflect.Type;
import java.util.List;

import static org.junit.Assert.*;

/**
 * Instrumented test, which will execute on an Android device.
 *
 * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
 */
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
    @Test
    public void useAppContext() {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
        assertEquals("com.ziyia.jsontest", appContext.getPackageName());

    }

    @Test
    public void GSONTest1() {
        String str = "{\"name\":\"年少有为\", \"age\":\"181\"}";
        Gson gson = new Gson();
        Person person = gson.fromJson(str, Person.class);
        System.out.println("person = " + person);
    }

    @Test
    public void GSONTest2() {
        String str = "[" +
                "{ \"name\": \"年少有为1\", \"age\":\"18\"}," +
                "{ \"name\": \"年少有为2\", \"age\":\"19\"}," +
                "{ \"name\": \"年少有为3\", \"age\":\"20\"}," +
                "{ \"name\": \"年少有为4\", \"age\":\"21\"}" +
                "]";

        System.out.println("str = " + str);
//        Type type = new TypeToken<List<Person>>(){}.getType();
        Type type = new TypeToken<List<Person>>(){}.getType();
        Gson gson = new Gson();

        List<Person> list = gson.fromJson(str, type);
        for (Person person : list) {
            System.out.println("person = " + person);
        }

    }
}
